<?php
namespace backend\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use backend\models\LoginForm;
use yii\filters\VerbFilter;
use backend\models\AdminInfo;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
					[
                    	'actions' => ['update-info'],
                    	'allow' => true,
                    	'roles' => ['@'],
                    ],
                    [
                        'actions' => ['logout', 'index'],
                        'allow' => true,
                        'roles' => ['?','@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    //'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->render('index');
        }
        return $this->redirect(['site/login']);
    }

    public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login() && $model->loginrecord()) {
//             if (\Yii::$app->user->can('tzx')){
//                 return $this->redirect('tzx/item');
//             }
        	$homeurl=Yii::$app->getHomeUrl();
        	//记录登录日志--suiyue
        	$model->loglogin();
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }
	
	    public function actionUpdateInfo($id)
    {
    	$model = AdminInfo::findOne($id);
    	$model->scenario = 'update_info';
    	if($model->load(Yii::$app->request->post()))
    	{
    		//echo '<br/><br/>';
    		//var_dump($model);
    		if($model->password !=null)$model->password_hash = Yii::$app->security->generatePasswordHash($model->password);
    		$model->save();
    		Yii::$app->session->setFlash('success','更改成功');
    		return $this->goBack();
    	}else{
    		return $this->render('update_info',[
    				'model'=>$model
    				]);
    	}
    	
    }
}
